package org.dairy.farms.dao.hibernate;

import org.dairy.farms.dao.LivestockDAO;
import org.dairy.farms.dao.generic.AbstractDAOImpl;
import org.dairy.farms.model.Livestock;
import org.dairy.farms.model.Notes;
import org.dairy.farms.model.NotesType;
import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: gduggira
 * Date: Jun 13, 2011
 * Time: 3:25:45 PM
 */
@Repository(value = "livestockDao")
public class LivestockDAOImpl extends AbstractDAOImpl<Livestock, Long> implements LivestockDAO {

    @Override
    public List<Livestock> findByProperty(String propertyName, Object propertyValue, int page, int start, int limit) {
        Criteria criteria = basePersistence.getSession().createCriteria(Livestock.class);
        criteria.add(Restrictions.like(propertyName, propertyValue)).setFirstResult(start).setMaxResults(limit);
        return criteria.list();
    }

    @Override
    public List<Livestock> findLivestockOfFarm(Long farmId, int page, int start, int limit) {
        Criteria criteria = basePersistence.getSession().createCriteria(Livestock.class);
        criteria.createCriteria("farm").add(Restrictions.eq("Id", farmId)).setFirstResult(start).setMaxResults(limit);
        return criteria.list();
    }

    @Override
    public Long findLivestockOfFarmCount(Long farmId) {
        Criteria criteria = basePersistence.getSession().createCriteria(Livestock.class);
        criteria.createCriteria("farm").add(Restrictions.eq("Id", farmId));
        criteria.setProjection(Projections.rowCount());
        return (Long) criteria.uniqueResult();
    }

    @Override
    public List<Livestock> findLivestockOfFarmByGender(Long farmId, Livestock.Gender gender) {
        Criteria criteria = basePersistence.getSession().createCriteria(Livestock.class);
        criteria.add(Restrictions.eq("gender", gender)).createCriteria("farm").add(Restrictions.eq("Id", farmId));
        return criteria.list();
    }

    @Override
    public List<Livestock> findByIds(Long[] livestockId) {
        Criteria criteria = basePersistence.getSession().createCriteria(Livestock.class);
        criteria.add(Restrictions.in("id", livestockId));
        return criteria.list();
    }

    @Override
    public Livestock findLivestockFarm(Long livestockId) {
        return findById(livestockId);
    }
}
